<template>
  <div class="traffic-check-container">
    <div class="header-section">
      <div class="header-content">
        <div class="controls-wrapper">
          <div class="control-group date-selector">
            <label class="control-label">日期范围：</label>
            <div class="date-inputs">
              <input type="date" v-model="startDate" class="date-input" />
              <span class="date-separator">至</span>
              <input type="date" v-model="endDate" class="date-input" />
            </div>
          </div>
        </div>
        
        <div class="controls-wrapper">
          <!-- 修改：将账号选择器改为一行显示 -->
          <div class="control-group account-selector">
            <label class="control-label">选择账户：</label>
            <div class="account-list">
              <div
                v-for="account in accountList"
                :key="account"
                :class="{ 'account-item': true, 'selected': selectedAccounts.includes(account) }"
                @click="toggleAccount(account)"
              >
                {{ account }}
                <!-- 添加选中状态下的删除按钮 -->
                <span 
                  v-if="selectedAccounts.includes(account)"
                  class="remove-account"
                  @click.stop="toggleAccount(account)"
                >
                  ×
                </span>
              </div>
            </div>
          </div>
          
          <button @click="fetchTrafficData" class="search-button">
            <i class="search-icon">🔍</i>
            查询数据
          </button>
        </div>
      </div>

      <div class="chart-controls-section">
        <div class="chart-type-buttons">
          <button
              @click="showLineChart"
              :class="{ active: chartType === 'line' }"
              class="chart-type-button"
          >
            折线图
          </button>
          <button
              @click="showBarChart"
              :class="{ active: chartType === 'bar' }"
              class="chart-type-button"
          >
            柱状图
          </button>
          <button
              @click="showPieChart"
              :class="{ active: chartType === 'pie' }"
              class="chart-type-button"
          >
            饼图
          </button>
          <!-- 将每日总计切换按钮放置在饼图按钮后方 -->
          <button
              @click="toggleDailyTotal"
              :class="{ active: showDailyTotal }"
              class="chart-type-button"
          >
            {{ showDailyTotal ? '隐藏每日总计' : '显示每日总计' }}
          </button>

          <label class="toggle-option">
            <input type="checkbox" v-model="showHourlyData" class="toggle-checkbox" />
            <span class="toggle-label">按小时显示</span>
          </label>

        </div>

      </div>

    </div>

    <!-- 添加每日总计卡片展示区域 -->
    <div v-if="showDailyTotal" class="daily-total-section">
      <h3 class="daily-total-title">每日总计</h3>
      <div class="daily-total-grid">
        <div 
          v-for="(data, date) in dailyTotalData" 
          :key="date" 
          class="daily-total-item"
        >
          <div class="date-label">{{ date }}</div>
          <div class="traffic-value-gb">{{ (data.total / 1024).toFixed(2) }} GB</div>
          <div class="traffic-value-mb">{{ data.total.toFixed(2) }} MB</div>
          <div class="account-details">
            <div 
              v-for="(accountTraffic, account) in data.accounts" 
              :key="account" 
              class="account-detail-item"
            >
              <span class="account-name">{{ account }}:</span>
              <span class="account-traffic">{{ (accountTraffic / 1024).toFixed(2) }} GB</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="chart-container-section">
      <div ref="trafficChart" class="chart-display"></div>
    </div>
    
    <div class="table-container-section">
      <div class="table-header">
        <h3 class="table-title">流量数据详情</h3>
      </div>
      <div class="table-wrapper">
        <table class="data-table">
          <thead>
            <tr>
              <th>账号</th>
              <th>流量 (GB)</th>
              <th>流量 (MB)</th>
              <th>日期</th>
              <th>小时</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in trafficData" :key="index" class="data-row">
              <td>{{ item.account }}</td>
              <td class="traffic-value">{{ (parseFloat(item.traffic) / 1024).toFixed(2) }}</td>
              <td class="traffic-value">{{ parseFloat(item.traffic).toFixed(2) }}</td>
              <td>{{ item.today }}</td>
              <td>{{ item.hour }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, nextTick} from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'TrafficCheck',
  setup() {
    const startDate = ref<string>('');
    const endDate = ref<string>('');
    const trafficData = ref<any[]>([]);
    const chart = ref<echarts.EChartsType | null>(null);
    const trafficChart = ref<HTMLDivElement | null>(null);
    // 恢复账号相关变量
    const accountList = ref<string[]>([]);
    const selectedAccounts = ref<string[]>([]);
    const chartType = ref<'line' | 'bar' | 'pie'>('line');
    // 添加按小时显示的开关
    const showHourlyData = ref<boolean>(false);
    // 添加每日总计显示开关
    const showDailyTotal = ref<boolean>(true);
    // 修改每日总计数据结构，支持按账号分类
    const dailyTotalData = ref<Record<string, {total: number, accounts: Record<string, number>}>>({});

    // 初始化日期
    const initDate = () => {
      // 从本地存储获取保存的日期，如果没有则使用默认值
      const savedStartDate = localStorage.getItem('trafficCheck_startDate');
      const savedEndDate = localStorage.getItem('trafficCheck_endDate');
      
      if (savedStartDate && savedEndDate) {
        startDate.value = savedStartDate;
        endDate.value = savedEndDate;
      } else {
        const now = new Date();
        // 修改：开始日期和结束日期默认都是当天
        startDate.value = now.toISOString().split('T')[0];
        endDate.value = now.toISOString().split('T')[0];
      }
    };

    // 获取账号列表
    const fetchAccountList = async () => {
      try {
        const response = await fetch(
          `https://api.cliproxy.com/traffic/records?key=sukv1yssuahwduiqmyvb&start=${startDate.value}&end=${endDate.value}`
        );
        const result = await response.json();
        
        if (result.code === 0) {
          // 恢复账号选择相关代码
          accountList.value = Array.from(new Set(result.data.map((item: any) => item.account)));
          
          // 从本地存储获取保存的选中账户
          const savedSelectedAccounts = localStorage.getItem('trafficCheck_selectedAccounts');
          if (savedSelectedAccounts) {
            // 使用保存的选中账户
            selectedAccounts.value = JSON.parse(savedSelectedAccounts).filter((account: string) => 
              accountList.value.includes(account)
            );
          } else {
            // 默认选择第一个账户（如果存在）
            selectedAccounts.value = accountList.value.length > 0 ? [accountList.value[0]] : [];
          }
        }
      } catch (error) {
        console.error('获取账号列表失败:', error);
      }
    };

    // 获取流量数据
    const fetchTrafficData = async () => {
      try {
        const response = await fetch(
          `https://api.cliproxy.com/traffic/records?key=sukv1yssuahwduiqmyvb&start=${startDate.value}&end=${endDate.value}`
        );
        const result = await response.json();
        
        if (result.code === 0) {
          // 恢复账号过滤相关代码，根据选择的账号过滤数据
          if (selectedAccounts.value.length > 0) {
            trafficData.value = result.data.filter((item: any) => 
              selectedAccounts.value.includes(item.account)
            );
          } else {
            trafficData.value = result.data;
          }
          // 计算每日总计数据
          calculateDailyTotalData();
          await nextTick();
          renderChart();
        }
      } catch (error) {
        console.error('获取流量数据失败:', error);
      }
    };

    // 计算每日总计数据
    const calculateDailyTotalData = () => {
      const dateTrafficMap: Record<string, {total: number, accounts: Record<string, number>}> = {};
      
      trafficData.value.forEach(item => {
        const date = item.today;
        const account = item.account;
        const traffic = parseFloat(item.traffic);
        
        if (!dateTrafficMap[date]) {
          dateTrafficMap[date] = {total: 0, accounts: {}};
        }
        
        dateTrafficMap[date].total += traffic;
        
        if (!dateTrafficMap[date].accounts[account]) {
          dateTrafficMap[date].accounts[account] = 0;
        }
        dateTrafficMap[date].accounts[account] += traffic;
      });
      
      dailyTotalData.value = dateTrafficMap;
    };

    // 撤回：恢复原来的账号选择处理函数
    const toggleAccount = (account: string) => {
      const index = selectedAccounts.value.indexOf(account);
      if (index > -1) {
        // 如果已选中，则取消选中
        selectedAccounts.value.splice(index, 1);
      } else {
        // 如果未选中，则选中
        selectedAccounts.value.push(account);
      }
      // 保存选中的账户到本地存储
      localStorage.setItem('trafficCheck_selectedAccounts', JSON.stringify(selectedAccounts.value));
      fetchTrafficData();
    };

    // 显示折线图
    const showLineChart = () => {
      chartType.value = 'line';
      renderChart();
    };

    // 显示柱状图
    const showBarChart = () => {
      chartType.value = 'bar';
      renderChart();
    };

    // 显示饼图
    const showPieChart = () => {
      chartType.value = 'pie';
      renderChart();
    };

    // 切换每日总计显示
    const toggleDailyTotal = () => {
      showDailyTotal.value = !showDailyTotal.value;
    };

    // 渲染图表
    const renderChart = () => {
      if (!trafficChart.value) return;
      
      if (chart.value) {
        chart.value.dispose();
      }
      
      chart.value = echarts.init(trafficChart.value);
      
      if (chartType.value === 'pie') {
        renderPieChart();
      } else {
        renderBarOrLineChart();
      }
    };

    // 渲染饼图
    const renderPieChart = () => {
      // 修改为按账号计算流量，而不是按日期
      const accountTrafficMap = new Map<string, number>();
      trafficData.value.forEach(item => {
        const current = accountTrafficMap.get(item.account) || 0;
        accountTrafficMap.set(item.account, current + parseFloat(item.traffic));
      });

      const pieData = Array.from(accountTrafficMap.entries()).map(([account, traffic]) => ({
        name: account,
        value: traffic / 1024  // 转换为GB
      }));

      const option = {
        title: {
          text: '账号流量分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} GB ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '流量',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      chart.value?.setOption(option);
    };

    // 渲染柱状图或折线图
    const renderBarOrLineChart = () => {
      // 处理数据
      // 恢复账号相关逻辑
      const accounts = Array.from(new Set(trafficData.value.map(item => item.account)));
      
      // 如果启用按小时显示，则使用小时数据
      if (showHourlyData.value) {
        renderHourlyChart(accounts);
        return;
      }
      
      const dates = Array.from(new Set(trafficData.value.map(item => item.today))).sort();
      
      // 修改：按账号分别计算每日总计数据用于图表展示
      const accountDateMap = new Map<string, Map<string, number>>();
      
      trafficData.value.forEach(item => {
        if (!accountDateMap.has(item.account)) {
          accountDateMap.set(item.account, new Map<string, number>());
        }
        const accountMap = accountDateMap.get(item.account)!;
        const current = accountMap.get(item.today) || 0;
        accountMap.set(item.today, current + parseFloat(item.traffic));
      });
      
      // 修改：为每个账号创建数据系列
      const seriesData = accounts.map(account => {
        const accountMap = accountDateMap.get(account) || new Map<string, number>();
        return {
          name: account,
          type: chartType.value,
          data: dates.map(date => (accountMap.get(date) || 0) / 1024), // 转换为GB
          label: {
            show: true,
            position: chartType.value === 'line' ? 'top' : 'insideTop',
            formatter: (params: any) => {
              return params.value.toFixed(2);
            },
            distance: 10,
            fontSize: 12
          }
        };
      });
      
      const option = {
        title: {
          text: '每日流量统计'
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params: any) => {
            let tooltipText = params[0].name + '<br/>';
            params.forEach((param: any) => {
              tooltipText += `${param.seriesName}: ${param.value.toFixed(2)} GB<br/>`;
            });
            return tooltipText;
          }
        },
        legend: {
          data: accounts
        },
        xAxis: chartType.value === 'bar' ? {
          type: 'category',
          data: dates,
          axisLabel: {
            margin: 50,
            rotate: 0, // 防止旋转导致位置异常
            align: 'center',
            verticalAlign: 'bottom',
            padding: [5, 0, 5, 0], // 上右下左，增加底部间距
            color: '#001529'
          }
        } : {
          type: 'category',
          data: dates,
          axisLabel: {
            margin: 50,
            rotate: 0,
            align: 'center',
            verticalAlign: 'bottom',
            padding: [5, 0, 5, 0]
          }
        },
        yAxis: {
          type: 'value',
          name: '流量 (GB)'
        },
        series: seriesData
      };
      
      chart.value?.setOption(option);
    };

    // 按小时渲染图表
    const renderHourlyChart = (accounts: string[]) => {
      // 当按小时显示时，只显示当天的数据
      const today = startDate.value;
      const todayData = trafficData.value.filter(item => item.today === today);
      
      // 创建24小时数组 - 简化格式只显示小时
      const hours = Array.from({ length: 24 }, (_, i) => {
        const hourStr = i.toString().padStart(2, '0');
        return `${hourStr}:00`;
      });
      
      // 按账号聚合每小时数据
      const accountHourlyMap = new Map<string, Map<number, number>>();
      todayData.forEach(item => {
        if (!accountHourlyMap.has(item.account)) {
          accountHourlyMap.set(item.account, new Map<number, number>());
        }
        const accountMap = accountHourlyMap.get(item.account)!;
        // 从hour字段中提取小时部分，格式为"YYYY-MM-DD HH:mm"
        const hour = parseInt(item.hour.split(' ')[1].split(':')[0]);
        // 使用当前记录的traffic值，而不是累加
        accountMap.set(hour, parseFloat(item.traffic));
      });

      // 为每个账号创建数据系列
      const seriesData = accounts.map(account => {
        const accountMap = accountHourlyMap.get(account) || new Map();
        return {
          name: account,
          type: chartType.value,
          data: Array.from({ length: 24 }, (_, i) => {
            const value = accountMap.get(i) || 0;
            return parseFloat((value / 1024).toFixed(2)); // 转换为GB
          }),
          label: {
            show: true,
            position: chartType.value === 'line' ? 'top' : 'insideTop',
            formatter: (params: any) => {
              // 当值为0时显示0.00而不是空
              if (params.value === 0) {
                return '0.00';
              }
              return params.value.toFixed(2);
            },
            // 避免折线图数值重叠
            distance: 10,
            fontSize: 12
          }
        };
      });

      const option = {
        title: {
          text: `小时流量统计`,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params: any) => {
            let tooltipText = params[0].name + '<br/>';
            params.forEach((param: any) => {
              tooltipText += `${param.seriesName}: ${param.value.toFixed(2)} GB<br/>`;
            });
            return tooltipText;
          }
        },
        legend: {
          data: accounts
        },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: {
            margin: 50,
            rotate: 0, // 防止旋转导致位置异常
            align: 'center',
            verticalAlign: 'bottom',
            padding: [5, 0, 5, 0], // 上右下左，增加底部间距
            color: '#001529'
          }
        },
        yAxis: {
          type: 'value',
          name: '流量 (GB)'
        },
        series: seriesData
      };
      
      chart.value?.setOption(option);
    };

    // 保存日期到本地存储
    const saveDateRange = () => {
      localStorage.setItem('trafficCheck_startDate', startDate.value);
      localStorage.setItem('trafficCheck_endDate', endDate.value);
    };

    // 初始化
    onMounted(() => {
      initDate();
      fetchAccountList().then(() => {
        fetchTrafficData();
      });
      window.addEventListener('resize', () => {
        if (chart.value) {
          chart.value.resize();
        }
      });
    });

    return {
      startDate,
      endDate,
      trafficData,
      trafficChart,
      fetchTrafficData,
      accountList,
      selectedAccounts,
      toggleAccount,
      chartType,
      showLineChart,
      showBarChart,
      showPieChart,
      toggleDailyTotal,
      showHourlyData,
      showDailyTotal,
      dailyTotalData,
      // 添加保存日期范围的方法
      saveDateRange
    };
  }
});
</script>

<style scoped>
.traffic-check-container {
  padding: 24px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.header-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.controls-wrapper {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  gap: 20px;
  width: 100%;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-label {
  font-weight: 500;
  color: #555;
  margin-right: 0;
  height: 32px;
  display: flex;
  align-items: center;
}

.date-inputs {
  display: flex;
  align-items: center;
  gap: 12px;
}

.date-input {
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  width: 140px;
  transition: border-color 0.2s;
}

.date-input:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.date-separator {
  color: #777;
  font-weight: 500;
}

/* 修改：更新账号选择器样式为一行显示 */
.account-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 添加删除按钮的样式 */
.remove-account {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 18px;
  height: 18px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 14px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.remove-account:hover {
  background-color: #ff7875;
}

.account-item {
  position: relative;
  padding: 8px 16px;
  background-color: #f1f3f5;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
  border: 2px solid transparent;
  text-align: center;
  min-width: 80px;
}

.account-item:hover {
  background-color: #e9ecef;
}

.account-item.selected {
  background-color: #007bff;
  color: white;
  border-color: #0056b3;
}

.search-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background-color: #42B180;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
  height: fit-content;
}

.search-button:hover {
  background-color: #0056b3;
}

.search-icon {
  font-size: 16px;
}

.chart-controls-section {
  margin-top: 20px;
  margin-bottom: 24px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.chart-type-buttons {
  display: flex;
  gap: 12px;
}

.chart-type-button {
  padding: 10px 20px;
  background-color: #f1f3f5;
  color: #495057;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.chart-type-button:hover {
  background-color: #e9ecef;
}

.chart-type-button.active {
  background-color: #007bff;
  color: white;
}

.toggle-option {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  user-select: none;
}

.toggle-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.toggle-label {
  font-size: 14px;
  color: #495057;
  font-weight: 500;
}

.chart-container-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  margin-bottom: 24px;
}

.chart-display {
  width: 100%;
  height: 500px;
}

/* 修改每日总计区域样式，增加账号详细信息样式 */
.daily-total-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
  margin-bottom: 24px;
}

.daily-total-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.daily-total-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.daily-total-item {
  text-align: center;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.date-label {
  font-weight: 500;
  color: #555;
  margin-bottom: 8px;
}

.traffic-value-gb {
  font-size: 18px;
  font-weight: 700;
  color: #007bff;
  margin-bottom: 4px;
}

.traffic-value-mb {
  font-size: 12px;
  color: #888;
  margin-bottom: 12px;
}

.account-details {
  border-top: 1px solid #dee2e6;
  padding-top: 12px;
  margin-top: 12px;
  text-align: left;
}

.account-detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
}

.account-detail-item:last-child {
  margin-bottom: 0;
}

.account-name {
  color: #6c757d;
}

.account-traffic {
  font-weight: 500;
  color: #495057;
}

.table-container-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.table-header {
  padding: 20px 24px;
  border-bottom: 1px solid #eee;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.table-wrapper {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table thead {
  background-color: #f8f9fa;
}

.data-table th {
  padding: 16px 24px;
  text-align: left;
  font-weight: 600;
  color: #495057;
  border-bottom: 1px solid #eee;
}

.data-table td {
  padding: 14px 24px;
  border-bottom: 1px solid #eee;
  color: #495057;
}

.data-row:hover {
  background-color: #f8f9fa;
}

.traffic-value {
  font-weight: 600;
  color: #007bff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .traffic-check-container {
    padding: 16px;
  }
  
  .header-section {
    padding: 20px;
  }
  
  .controls-wrapper {
    flex-direction: column;
    align-items: stretch;
  }
  
  .control-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .date-inputs {
    justify-content: space-between;
  }
  
  .date-input {
    width: calc(50% - 20px);
  }
  
  .search-button {
    align-self: flex-start;
  }
  
  .chart-controls-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .chart-type-buttons {
    flex-wrap: wrap;
  }
  

  
  .chart-display {
    height: 400px;
  }
}

@media (max-width: 480px) {
  
  .chart-type-button {
    padding: 8px 16px;
    font-size: 13px;
  }
  
  .toggle-label {
    font-size: 13px;
  }
  
  .data-table th,
  .data-table td {
    padding: 12px 16px;
  }
}
</style>